import base64
import requests


def encode_image_to_base64(image_path):
    """
    将指定路径的图片文件编码为 Base64 字符串。
    :param image_path: 图片文件的路径
    :return: 图片的 Base64 编码字符串，如果出现错误则返回 None
    """
    try:
        with open(image_path, 'rb') as image_file:
            return base64.b64encode(image_file.read()).decode('utf-8')
    except FileNotFoundError:
        print(f"错误：未找到图片文件 {image_path}")
    except Exception as e:
        print(f"读取图片文件时出现错误: {e}")
    return None


def send_image_query(model, query, encoded_images, url):
    """
    向指定的 API 发送图片查询请求。
    :param model: 使用的模型名称
    :param query: 查询的问题
    :param encoded_images: 图片的 Base64 编码字符串列表
    :param url: API 的请求 URL
    :return: API 的响应结果，如果出现错误则返回 None
    """
    data = {
        "model": model,
        "prompt": query,
        "stream": False,
        "images": encoded_images
    }
    try:
        response = requests.post(url, json=data)
        response.raise_for_status()
        return response.json()
    except requests.RequestException as e:
        print(f"请求 API 时出现错误: {e}")
    except ValueError:
        print("无法解析 API 的响应为 JSON 格式")
    return None


if __name__ == "__main__":
    image_path = 'resources/3.png'
    query = '这张图片描述了什么?'
    api_url = "http://localhost:11434/api/generate"
    model_name = "minicpm-v"

    encoded_image = encode_image_to_base64(image_path)
    if encoded_image:
        result = send_image_query(model_name, query, [encoded_image], api_url)
        if result:
            print(result)

